#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import json
import time
from datetime import datetime
import io
import base64
import re

# 尝试导入可能需要安装的依赖包
try:
    from PIL import Image, ImageDraw, ImageFont
    PIL_AVAILABLE = True
except ImportError:
    PIL_AVAILABLE = False
    Image = ImageDraw = ImageFont = None
    print("警告: 未找到PIL库，导出图片功能将不可用")
    print("请运行: pip install pillow")

try:
    import weasyprint
except ImportError:
    weasyprint = None
    print("警告: 未找到weasyprint库，导出PDF功能将不可用")
    print("请运行: pip install weasyprint")
except OSError as e:
    weasyprint = None
    print("错误: 导入weasyprint时发生系统错误")
    print(f"详细信息: {e}")
    print("这通常是因为缺少系统依赖库。")
    print("请安装GTK+运行时库：")
    print("下载地址：https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases")
    print("安装后请重启系统")

class BangumiExporter:
    """B站追番列表导出工具"""
    
    def __init__(self, data_file='bangumi_data.json', output_dir='bangumi_exports'):
        self.data_file = data_file
        self.output_dir = output_dir
        self.html_dir = 'bangumi_page'
        
        # 创建导出目录
        os.makedirs(self.output_dir, exist_ok=True)
    
    def load_data(self):
        """加载番剧数据"""
        try:
            with open(self.data_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            print(f"错误: 找不到数据文件 {self.data_file}")
            return None
        except json.JSONDecodeError:
            print(f"错误: 数据文件 {self.data_file} 格式不正确")
            return None
    
    def export_to_pdf(self, filter_status=None):
        """导出追番列表为PDF"""
        if weasyprint is None:
            # 已经在前面的异常处理中打印了错误信息
            return None
            
        try:
            # 尝试导入weasyprint的子模块以检测系统依赖
            from weasyprint import HTML
        except OSError as e:
            print("错误: 缺少系统依赖库，无法导出PDF")
            print(f"详细信息: {e}")
            print("请安装GTK+运行时库：")
            print("下载地址：https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer/releases")
            print("安装后请重启系统")
            return None
            
        # 检查HTML页面是否已生成
        index_html = os.path.join(self.html_dir, 'index.html')
        if not os.path.exists(index_html):
            print(f"错误: HTML页面 {index_html} 不存在，请先生成HTML页面")
            return None
        
        # 生成导出用的HTML
        export_html = self._generate_export_html(filter_status)
        if not export_html:
            return None
        
        # 生成PDF文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        status_text = f"_{filter_status}" if filter_status else ""
        pdf_filename = os.path.join(self.output_dir, f"bangumi_list{status_text}_{timestamp}.pdf")
        
        try:
            # 使用WeasyPrint将HTML转换为PDF
            print("正在生成PDF文件...")
            weasyprint.HTML(string=export_html).write_pdf(pdf_filename)
            print(f"PDF文件已生成: {pdf_filename}")
            return pdf_filename
        except Exception as e:
            print(f"生成PDF时出错: {e}")
            return None
    
    def export_to_image(self, filter_status=None):
        """导出追番列表为图片"""
        if not PIL_AVAILABLE:
            print("错误: PIL库未安装，无法导出图片")
            print("请运行: pip install pillow")
            return None
            
        # 加载番剧数据
        bangumi_data = self.load_data()
        if not bangumi_data:
            return None
        
        # 筛选数据
        bangumi_list = bangumi_data['data']
        if filter_status:
            bangumi_list = [b for b in bangumi_list if b['status'] == filter_status]
        
        if not bangumi_list:
            print(f"没有找到{filter_status or '任何'}状态的番剧")
            return None
        
        try:
            # 设置图片参数
            padding = 20
            card_width = 300
            card_height = 150
            cards_per_row = 3
            row_count = (len(bangumi_list) + cards_per_row - 1) // cards_per_row
            
            # 创建图片
            img_width = padding + (card_width + padding) * cards_per_row
            img_height = padding + (card_height + padding) * row_count + 60  # 额外空间用于标题
            
            # 创建白色背景图片
            image = Image.new('RGB', (img_width, img_height), color=(255, 255, 255))
            draw = ImageDraw.Draw(image)
            
            # 尝试加载字体，如果失败则使用默认字体
            try:
                # 尝试加载微软雅黑字体
                title_font = ImageFont.truetype("msyh.ttc", 24)
                text_font = ImageFont.truetype("msyh.ttc", 12)
            except IOError:
                # 使用默认字体
                title_font = ImageFont.load_default()
                text_font = ImageFont.load_default()
            
            # 绘制标题
            title = f"我的B站追番列表 - {filter_status or '全部'}"
            title_width = draw.textlength(title, font=title_font)
            draw.text(((img_width - title_width) // 2, padding), title, font=title_font, fill=(251, 114, 153))
            
            # 绘制番剧卡片
            for i, bangumi in enumerate(bangumi_list):
                row = i // cards_per_row
                col = i % cards_per_row
                
                x = padding + col * (card_width + padding)
                y = padding + row * (card_height + padding) + 60  # 标题下方60像素
                
                # 绘制卡片背景
                draw.rectangle([x, y, x + card_width, y + card_height], fill=(244, 244, 244), outline=(200, 200, 200))
                
                # 绘制番剧标题
                title = bangumi['title']
                if len(title) > 15:
                    title = title[:15] + "..."
                draw.text((x + 10, y + 10), title, font=text_font, fill=(51, 51, 51))
                
                # 绘制番剧状态
                status_text = "追番中" if bangumi['status'] == "watching" else "已看完"
                status_color = (46, 204, 113) if bangumi['status'] == "watching" else (35, 173, 229)
                draw.text((x + 10, y + 30), status_text, font=text_font, fill=status_color)
                
                # 绘制评分
                draw.text((x + 10, y + 50), f"评分: {bangumi['score']}", font=text_font, fill=(102, 102, 102))
                
                # 绘制进度
                draw.text((x + 10, y + 70), f"进度: {bangumi['progress']}", font=text_font, fill=(102, 102, 102))
            
            # 绘制页脚
            footer_text = f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
            footer_width = draw.textlength(footer_text, font=text_font)
            draw.text(((img_width - footer_width) // 2, img_height - 30), footer_text, font=text_font, fill=(102, 102, 102))
            
            # 保存图片
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            status_text = f"_{filter_status}" if filter_status else ""
            img_filename = os.path.join(self.output_dir, f"bangumi_list{status_text}_{timestamp}.png")
            image.save(img_filename)
            
            print(f"图片已生成: {img_filename}")
            return img_filename
        except Exception as e:
            print(f"生成图片时出错: {e}")
            return None
    
    def _generate_export_html(self, filter_status=None):
        """生成用于导出的HTML"""
        # 加载番剧数据
        bangumi_data = self.load_data()
        if not bangumi_data:
            return None
        
        # 筛选数据
        bangumi_list = bangumi_data['data']
        if filter_status:
            bangumi_list = [b for b in bangumi_list if b['status'] == filter_status]
        
        if not bangumi_list:
            print(f"没有找到{filter_status or '任何'}状态的番剧")
            return None
        
        # 读取CSS文件
        css_file = os.path.join(self.html_dir, 'css', 'style.css')
        try:
            with open(css_file, 'r', encoding='utf-8') as f:
                css_content = f.read()
                
                # 修改CSS以适应打印
                css_content = css_content.replace('@media (max-width: 768px)', '@media print, (max-width: 768px)')
                css_content += '''
                @media print {
                    body {
                        background-color: white;
                    }
                    .header, .filter-container, .footer {
                        box-shadow: none;
                    }
                    #back-to-top {
                        display: none !important;
                    }
                    .bangumi-card {
                        break-inside: avoid;
                    }
                    .card-hover {
                        display: none !important;
                    }
                }
                '''
        except FileNotFoundError:
            print(f"警告: 找不到CSS文件 {css_file}，将使用默认样式")
            css_content = '''
            body { font-family: Arial, sans-serif; background-color: white; }
            .container { max-width: 1200px; margin: 0 auto; padding: 15px; }
            h1 { color: #FB7299; text-align: center; }
            .bangumi-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
            .bangumi-card { border: 1px solid #ddd; border-radius: 8px; overflow: hidden; }
            .card-info { padding: 15px; }
            .bangumi-title { font-weight: bold; margin-bottom: 10px; }
            .bangumi-meta { color: #666; font-size: 14px; }
            .footer { text-align: center; margin-top: 30px; color: #666; }
            @media print {
                .bangumi-card { break-inside: avoid; }
            }
            '''
        
        # 生成HTML内容
        status_text = filter_status if filter_status else "全部"
        if filter_status == "watching":
            status_text = "追番中"
        elif filter_status == "finished":
            status_text = "已看完"
            
        html_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的B站追番列表 - {status_text}</title>
    <style>
    {css_content}
    </style>
</head>
<body>
    <header class="header">
        <div class="container">
            <div class="logo">
                <h1>我的B站追番列表 - {status_text}</h1>
            </div>
        </div>
    </header>
    
    <main class="main-content">
        <div class="container">
            <div class="bangumi-grid">
'''
        
        # 生成番剧卡片
        for bangumi in bangumi_list:
            status_class = bangumi['status']
            status_text = "追番中" if status_class == "watching" else "已看完"
            
            html_content += f'''
                <div class="bangumi-card" data-status="{status_class}">
                    <div class="card-info">
                        <h3 class="bangumi-title">{bangumi['title']}</h3>
                        <div class="bangumi-meta">
                            <p>评分: {bangumi['score']}</p>
                            <p>进度: {bangumi['progress']}</p>
                            <p>状态: {status_text}</p>
                        </div>
                    </div>
                </div>'''
        
        # 完成HTML内容
        html_content += f'''
            </div>
        </div>
    </main>
    
    <footer class="footer">
        <div class="container">
            <p>数据更新时间: {bangumi_data['update_time']}</p>
            <p>导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        </div>
    </footer>
</body>
</html>'''
        
        return html_content

def install_required_packages():
    """安装所需的依赖包"""
    missing_packages = []
    
    # 检查PIL
    try:
        import PIL
    except ImportError:
        missing_packages.append("pillow")
    
    # 检查weasyprint
    try:
        import weasyprint
    except ImportError:
        print("跳过weasyprint安装，如需PDF导出功能请手动安装")
        # missing_packages.append("weasyprint")
    
    # 如果有缺失的包，尝试安装
    if missing_packages:
        print(f"正在安装所需的依赖包: {', '.join(missing_packages)}...")
        try:
            import subprocess
            for package in missing_packages:
                print(f"安装 {package}...")
                subprocess.check_call([sys.executable, "-m", "pip", "install", package])
            print("依赖包安装完成")
        except Exception as e:
            print(f"安装依赖包时出错: {e}")
            print("请手动安装以下包:")
            for package in missing_packages:
                print(f"pip install {package}")

if __name__ == "__main__":
    import sys
    
    # 安装所需的依赖包
    install_required_packages()
    
    exporter = BangumiExporter()
    
    if len(sys.argv) > 1:
        export_type = sys.argv[1].lower()
        filter_status = sys.argv[2] if len(sys.argv) > 2 else None
        
        if export_type == "pdf":
            exporter.export_to_pdf(filter_status)
        elif export_type == "image":
            exporter.export_to_image(filter_status)
        else:
            print("未知的导出类型，请使用 'pdf' 或 'image'")
    else:
        print("使用方法: python export_utils.py [pdf|image] [watching|finished]")
        print("例如: python export_utils.py pdf watching  # 导出追番中的番剧为PDF")